package com.hmdp.intercepter;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.Exception.NotLoginException;
import com.hmdp.domain.dto.UserDTO;
import com.hmdp.properties.JwtProperties;
import com.hmdp.utils.JwtUtil;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.content.MessageContent.USER_NOT_LOGIN;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //获取token
        String tokenName = jwtProperties.getUserTokenName();
        String token = request.getHeader(tokenName);
        //校验令牌
        try {
            log.info("Jwt校验:{}", token);
            JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Map entries = redisTemplate.opsForHash().entries(token);
            if (entries.isEmpty()){
                throw new NotLoginException(USER_NOT_LOGIN);
            }
            UserDTO userDTO;
            userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
            UserHolder.saveUser(userDTO);
            //重置redis过期时间
            redisTemplate.expire(token, jwtProperties.getUserTtl()/1000, TimeUnit.SECONDS);
            log.info("当前用户信息:{}", userDTO);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error(USER_NOT_LOGIN);
            response.setStatus(401);
            return false;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserHolder.removeUser();
    }
}
